//
//  BPScreenShotManager.m
//  BPScreenManager_Example
//
//  Created by SiYugui on 2020/4/30.
//  Copyright © 2020年 xuhongji. All rights reserved.
//

#import "BPScreenShotManager.h"
#import "BPScreenFileManager.h"
#import "BPScreenImage.h"

static float const kCompression = 0.9;

@implementation BPScreenShotManager

static BPScreenShotManager *shoter = nil;

+ (instancetype)shareInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shoter = [[BPScreenShotManager alloc] init];
        shoter.cache = YES;
    });
    return shoter;
}

- (void)addShotNotificationWithDelegate:(id)delegate{
    if (delegate) {
        self.delegate = delegate;
    }
    [self registShotNotification];
}

- (void)registShotNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidTakeScreenShot:) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
}

- (void)removeShotNotification{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationUserDidTakeScreenshotNotification object:nil];
    self.delegate = nil;
}

-(void)userDidTakeScreenShot:(NSNotification*)notification{
    UIImage *shotImage = [BPScreenImage currentScreenImage];
    if (self.cache) {
        NSString *filePath = [BPScreenFileManager filePath];
        NSString *fileName = [BPScreenFileManager fileName];
        NSData *fileData = [BPScreenFileManager dataInJpegFormatWithImage:shotImage compressionQuality:kCompression];
        [BPScreenFileManager saveFile:fileData fileName:fileName ToPath:filePath];
    }
    
    self.lastShotImage = shotImage;
    
    if (self.delegate == nil) {
        return;
    }
    
    if ([self.delegate respondsToSelector:@selector(screenShot:didShotWithScreenImage:)]) {
        [self.delegate screenShot:shoter didShotWithScreenImage:shotImage];
    }else{
        NSAssert(NO, @"未实现 screenShot:didShotWithScreenImage:方法");
    }
}

@end
